package com.xzy.web.controller;

import com.xzy.custom.*;
import com.xzy.entities.BookInformation;
import com.xzy.entities.BookRepertory;
import com.xzy.entities.BookType;
import com.xzy.security.UserUtils;
import com.xzy.service.BookInformationService;
import com.xzy.service.BookRepertoryService;
import com.xzy.service.BookTypeService;
import com.xzy.web.form.BookInformationForm;
import com.xzy.web.form.BookRepertoryForm;
import com.xzy.web.form.BookTypeForm;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

/**
 * TODO70
 *
 * @author Administrator
 * ClassName: BookController
 * date: 2021/11/23 15:12
 */
@Controller
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookTypeService bookTypeService;
    @Autowired
    private BookInformationService bookInformationService;
    @Autowired
    private BookRepertoryService bookRepertoryService;
    @Autowired
    private LogUtils logUtils;
    @Autowired
    private UserUtils userUtils;

    @RequestMapping("/bookType")
    public String bookType(){
        return "admin/book/bookType/manage";
    }

    @RequestMapping("/findAllBookType")
    @ResponseBody
    public ResultMap<List<BookType>> findAllBookType(Page page,@RequestParam("limit")int limit, @Param("name") String name){
            page.setRows(limit);
            page.setPage((page.getPage()-1)*limit);
            Integer total = bookTypeService.findBookInformationCount(page,name);
            List<BookType> list = bookTypeService.findAllBookType(page,name);
            return new ResultMap<List<BookType>>("",list,0,total);

    }

    @RequestMapping("/bookInformation")
    public String bookInformation(ModelMap map){
        map.put("bookTypeList",bookTypeService.findAllBookType1());
        return "admin/book/bookInformation/manage";
    }

    @RequestMapping("/findAllBookInformation")
    @ResponseBody
    public ResultMap<List<BookInformation>> findAllBookInformation(Page page,@RequestParam("limit")int limit,@Param("name")String name){
        page.setRows(limit);
        page.setPage((page.getPage()-1)*limit);
        Integer total = bookInformationService.findBookInformationCount(page,name);
        List<BookInformation> list = bookInformationService.findAllBookInformation(page,name);
        return new ResultMap<List<BookInformation>>("",list,0,total);
    }

    @RequestMapping("/bookRepertory")
    public String bookRepertory(){
        return "admin/book/bookRepertory/manage";
    }

    @RequestMapping("/findAllBookRepoertory")
    @ResponseBody
    public ResultMap<List<BookRepertory>> findAllBookRepoertory(Page page,@RequestParam("limit")int limit, @Param("name")String name){
        page.setRows(limit);
        page.setPage((page.getPage() - 1) * limit);
        Integer total = bookRepertoryService.findBookRepertoryCount(page,name);
        List<BookRepertory> list = bookRepertoryService.findAllBookRepertory(page,name);
        return new ResultMap<List<BookRepertory>>("", list, 0, total);
    }

    @RequestMapping("/bookInformationEdit")
    @ResponseBody
    public String bookInformationEdit(){
        return "informationEdit";
    }

    @RequestMapping("/informationEdit")
    public String informationEdit(BookInformationForm form, ModelMap map){
        map.put("bookType",bookTypeService.findAllBookType1());
        BookInformation model = new BookInformation();
        Integer id = form.getId();
        if (id != null){
            model = bookInformationService.findById(id);
        }
        map.put("model",model);
        return "admin/book/bookInformation/edit";
    }

    @RequestMapping("/bookTypeEdit")
    @ResponseBody
    public String bookTypeEdit(){
        return "typeEdit";
    }

    @RequestMapping("/typeEdit")
    public String typeEdit(BookTypeForm form, ModelMap map){
        BookType model = new BookType();
        Integer id = form.getId();
        System.out.println(id);
        if (id != null){
            model = bookTypeService.findById(id);
        }
        map.put("model",model);
        return "admin/book/bookType/edit";
    }

    @RequestMapping("/bookRepoertoryEdit")
    @ResponseBody
    public String bookRepoertoryEdit(){
        return "repoertoryEdit";
    }

    @RequestMapping("/repoertoryEdit")
    public String repoertoryEdit(BookTypeForm form, ModelMap map){
        map.put("bookInformation",bookInformationService.findAllBook());
        BookRepertory model = new BookRepertory();
        Integer id = form.getId();
        System.out.println(id);
        if (id != null){
            model = bookRepertoryService.findById(id);
        }
        map.put("model",model);
        return "admin/book/bookRepertory/edit";
    }

    @RequestMapping("/saveInformation")
    @ResponseBody
    public Object bookInformationSave(BookInformationForm form){
        if("".equals(form.getBookName())){
            return new AjaxResult(false,"请填写书名！");
        }else if("".equals(form.getAuthor())){
            return new AjaxResult(false,"请填写作者！");
        }else if("".equals(form.getPress())){
            return new AjaxResult(false,"请填写出版社！");
        }else if(form.getType() == null){
            return new AjaxResult(false,"请选择图书类型！");
        }else if("".equals(form.getIsbn())){
            return new AjaxResult(false,"请填写isbn码！");
        }else{
            if (form.getId() != null){
                bookInformationService.updataById(form);
                logUtils.log(userUtils.getUser().getUsername(),"修改id为"+form.getId()+"的图书信息");
            }else{
                bookInformationService.insertInformation(form);
                logUtils.log(userUtils.getUser().getUsername(),"新增"+form.getBookName()+"图书信息");
            }
        }
        return new AjaxResult("数据保存成功");
    }

    @RequestMapping("/saveType")
    @ResponseBody
    public Object saveType(BookTypeForm form){
        try {
            if ("".equals(form.getType())){
                return new AjaxResult(false,"请填写类型名称！");
            }else if("".equals(form.getCode())){
                return new AjaxResult(false,"请填写类型代码！");
            }else{
                if (form.getId() != null){
                    bookTypeService.updateById(form);
                    logUtils.log(userUtils.getUser().getUsername(),"修改id为"+form.getId()+"的图书类型信息");
                }else{
                    bookTypeService.insertType(form);
                    logUtils.log(userUtils.getUser().getUsername(),"新增"+form.getType());
                }
            }
            return new AjaxResult("数据保存成功！");
        }catch (Exception e){
            return new AjaxResult(false,"数据保存失败！");
        }
    }

    @RequestMapping("/saveRepoertory")
    @ResponseBody
    public Object saveRepoertory(BookRepertoryForm form){
        try {
            BookRepertory quantity = bookRepertoryService.findByBookId(form.getBookId());
            if (form.getBookId() == null){
                return new AjaxResult(false,"请选择图书！");
            }else if(form.getQuantity() == null){
                return new AjaxResult(false,"请填写图书数量！");
            }else{
                BookInformation book = bookInformationService.findById(form.getBookId());
                if (form.getId() != null){
                    bookRepertoryService.updateById(form);
                    logUtils.log(userUtils.getUser().getUsername(),"修改"+book.getBookName()+"库存");
                }else {
                    if (quantity == null){
                        bookRepertoryService.insertRepertory(form);
                        logUtils.log(userUtils.getUser().getUsername(),"新增"+book.getBookName()+"库存");
                    }else{
                        form.setQuantity(quantity.getQuantity()+form.getQuantity());
                        form.setId(quantity.getId());
                        bookRepertoryService.updateById(form);
                        logUtils.log(userUtils.getUser().getUsername(),"修改"+book.getBookName()+"库存");
                    }
                }
            }
            return new AjaxResult("数据保存成功！");
        }catch (Exception e){
            return new AjaxResult(false,"数据保存失败！");
        }
    }

    @RequestMapping("/delBookInformation")
    @ResponseBody
    public Object delBookInformation(String ids){
        try {
            String[] split = ids.split(",");
            for (int i = 0; i < split.length;i++){
                bookInformationService.deleteById(Integer.parseInt(split[i]));
                logUtils.log(userUtils.getUser().getUsername(),"删除图书信息");
            }
            return new AjaxResult("删除成功！");
        }catch (Exception e){
            return new AjaxResult(false, "数据删除失败");
        }
    }

    @RequestMapping("/delBookType")
    @ResponseBody
    public Object delBookType(String ids){
        try {
            String[] split = ids.split(",");
            for (int i = 0; i < split.length;i++){
                bookTypeService.deleteById(Integer.parseInt(split[i]));
                logUtils.log(userUtils.getUser().getUsername(),"删除图书类型");
            }
            return new AjaxResult("删除成功！");
        }catch (Exception e){
            return new AjaxResult(false, "数据删除失败");
        }
    }

    @RequestMapping("/delBookRepoertory")
    @ResponseBody
    public Object delBookRepoertory(String ids){
        try {
            String[] split = ids.split(",");
            for (int i = 0; i < split.length;i++){
                bookRepertoryService.deleteById(Integer.parseInt(split[i]));
                logUtils.log(userUtils.getUser().getUsername(),"删除图书库存");
            }
            return new AjaxResult("删除成功！");
        }catch (Exception e){
            return new AjaxResult(false, "数据删除失败");
        }
    }


    @RequestMapping("/upload")
    @ResponseBody
    public Object upload(MultipartFile file,Integer id){
        System.err.println(file);
        System.err.println(id);
        String uuid = UUID.randomUUID().toString();
        Boolean boole = bookInformationService.saveFile(file,uuid,id);
        BookInformation information = bookInformationService.findByUuid(uuid);
        if (boole){
            return new AjaxResult(true, uuid, information.getId());
        }else{
            return new AjaxResult(true, file.getOriginalFilename());
        }
    }

    /**
     * 下载
     * @param uuid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download")
    @ResponseBody
    private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
        bookInformationService.download(uuid, request, response);
    }
}
